package cn.edu.lingnan.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Component;

import java.util.Properties;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Component
public class EmailUtil {

    private static RedisTemplate<String, Object> redisTemplate;

    private static final long CAPTCHA_EXPIRE_TIME = 120; // 验证码过期时间为120秒
    private static final String CAPTCHA_PREFIX = "captcha:";

    private static final String HOST = "smtp.163.com";
    private static final int PORT = 465;
    private static final String USERNAME = "13414863534@163.com";
    private static final String PASSWORD = "SVmKDiB2jmhbVHjq";
    private static final String PROTOCOL = "smtps";
    private static final String FROM_EMAIL = "13414863534@163.com";
    private static final String SUBJECT = "您的验证码";

    private static JavaMailSender mailSender;

    // 使用 @Autowired 静态注入 RedisTemplate
    @Autowired
    public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
        EmailUtil.redisTemplate = redisTemplate;
    }

    // 初始化 JavaMailSender
    static {
        JavaMailSenderImpl mailSenderImpl = new JavaMailSenderImpl();
        mailSenderImpl.setHost(HOST);
        mailSenderImpl.setPort(PORT);
        mailSenderImpl.setUsername(USERNAME);
        mailSenderImpl.setPassword(PASSWORD);
        mailSenderImpl.setProtocol(PROTOCOL);

        Properties properties = new Properties();
        properties.put("mail.smtp.connectiontimeout", "5000");
        properties.put("mail.smtp.timeout", "3000");
        properties.put("mail.smtp.writetimeout", "5000");
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.smtp.starttls.required", "true");

        mailSenderImpl.setJavaMailProperties(properties);
        mailSenderImpl.setDefaultEncoding("UTF-8");
        mailSender = mailSenderImpl;
    }

    // 生成6位随机数验证码
    private static String generateRandomCode() {
        Random random = new Random();
        int code = 100000 + random.nextInt(900000);
        return String.valueOf(code);
    }

    // 发送验证码并将其存入 Redis
    public static String sendCaptcha(String email, String sessionId) {
        String verificationCode = generateRandomCode();
        String redisKey = CAPTCHA_PREFIX + email + ":" + sessionId;

        // 将验证码存入 Redis，并设置过期时间
        redisTemplate.opsForValue().set(redisKey, verificationCode, CAPTCHA_EXPIRE_TIME, TimeUnit.SECONDS);

        // 构建邮件消息
        String text = "您的验证码是：" + verificationCode + "，请在5分钟内使用。";
        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo(email);
        message.setSubject(SUBJECT);
        message.setText(text);
        message.setFrom(FROM_EMAIL);

        // 发送邮件
        mailSender.send(message);
        System.out.println("验证码已发送至 " + email + "，验证码为：" + verificationCode);
        return verificationCode;
    }

    // 校验验证码
    public static boolean verifyCaptcha(String email, String inputCaptcha, String sessionId) {
        String redisKey = CAPTCHA_PREFIX + email + ":" + sessionId;

        // 从 Redis 中获取验证码
        String storedCaptcha = (String) redisTemplate.opsForValue().get(redisKey);

        // 校验验证码是否匹配
        if (storedCaptcha != null && storedCaptcha.equals(inputCaptcha)) {
            // 验证成功后删除验证码
            redisTemplate.delete(redisKey);
            return true;
        }
        return false;
    }
}
